﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TerminalTick.Models;

namespace TerminalTick.SignalR
{    
    public class TerminalStore : ITerminalStore
    {
        //thread safe dictionary
        private static ConcurrentDictionary<string, TerminalPoint> _points =
            new ConcurrentDictionary<string, TerminalPoint>();

        //singleton instance
        private static readonly Lazy<TerminalStore> _instance =
            new Lazy<TerminalStore>(() => new TerminalStore());

        private TerminalStore()
        {
        }

        public static TerminalStore Instance
        {
            get
            {
                return _instance.Value;
            }
        }

        public TerminalPoint Get(string id)
        {
            if (_points.ContainsKey(id))
            {
                return _points[id];
            }
            return null;
        }

        public List<TerminalPoint> GetAll()
        {
            return _points.Values.ToList();
        }

        public bool Add(TerminalPoint point)
        {
            if (_points.ContainsKey(point.Id))
            {
                throw new Exception(String.Format("the point({0},{1}) exist.", point.X, point.Y));
            }
            return _points.TryAdd(point.Id, point);            
        }

        public bool Delete(string id)
        {
            if (_points.ContainsKey(id))
            {
                TerminalPoint tp = null;
                return _points.TryRemove(id, out tp);
            }
            return false;
        }
    }
}